export default class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  on(type, handler) {
    if (!this._events[type]) {
      this._events[type] = new Set()
    }
    this._events[type].add(handler)
  }

  off(type, handler) {
    if (!this._events[type]) return
    if (handler) {
      this._events[type].delete(handler)
    } else {
      this._events[type].clear()
    }
    if (this._events[type].size === 0) {
      delete this._events[type]
    }
  }

  emit(type, payload) {
    if (!this._events[type]) return
    this._events[type].forEach((handler) => {
      try {
        handler(payload)
      } catch (error) {
        console.error('[EventEmitter] handler error', error)
      }
    })
  }
}
